package com.neighbor.neighborhooduser.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neighbor.neighborhooduser.pojo.MallOrders;
import com.neighbor.neighborhooduser.pojo.MallProducts;
import com.neighbor.neighborhooduser.pojo.Posts;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.service.IMallOrdersService;
import com.neighbor.neighborhooduser.service.IPostsService;
import com.neighbor.neighborhooduser.service.IUsersService;
import com.neighbor.neighborhooduser.utils.JwtUtils;
import com.neighbor.neighborhooduser.utils.RedisUtils;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 用户基本信息表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:05
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    IUsersService usersService; //用户表代理对象

    @Autowired
    private IPostsService postsService;

    @Autowired
    private IMallOrdersService mallOrdersService;
    /**
     * 获取当前登录用户信息
     *
     * 本方法通过JWT令牌验证用户身份，并从Redis中获取完整的用户信息。
     * 流程说明：
     * 1. 从请求头获取JWT令牌
     * 2. 验证令牌是否存在
     * 3. 解析JWT获取用户基本信息
     * 4. 验证Redis中是否存在有效的会话
     * 5. 返回Redis中存储的完整用户信息
     *
     * @param request HttpServletRequest对象，用于获取请求头信息
     * @return ResponseMsg 响应消息对象，包含操作结果和用户信息
     *         - 成功：返回SUCCESS状态码和用户信息
     *         - 失败：返回错误状态码和错误信息
     *          可能错误：
     *          - REQUEST_ERROR: 未提供身份凭证
     *          - TOKEN_ERROR: 会话已过期或无效凭证
     */
    @RequestMapping("getUserInfo")
    //利用token检验版本
    ResponseMsg getUserInfo(HttpServletRequest request) {
        // 1. 从请求头获取JWT令牌
        String jwtToken = request.getHeader("token");

        // 2. 验证token是否存在且有效
        if (jwtToken == null || jwtToken.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, "未提供身份凭证");
        }

        try {
            // 3. 解析JWT获取用户信息
            Claims claims = JwtUtils.parseJWT(jwtToken);

            // 4. 将JWT中的用户信息转换为Users对象
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);

            // 5. 验证Redis中的token有效性
            // 使用用户手机号作为Redis key
            String idKey = String.valueOf(tokenUser.getUserId());

            // 6. 检查Redis中是否存在该会话
            if (!redisUtils.hasKey(idKey)) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "不存在该会话");
            }

            // 7. 从Redis获取并返回的token
            String realToken = redisUtils.get(idKey).toString();

            Claims claims1 = JwtUtils.parseJWT(realToken);

            Users resUser = JSON.parseObject(claims1.getSubject(), Users.class);

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, resUser);


        } catch (Exception ex) {
            // 8. 异常处理
            // 捕获所有JWT解析异常，统一返回无效凭证
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
        }
    }

    /**
     *      检测用户端登录
     * @param account 手机号
     * @param password  账号密码
     * @return  返回信息
     */
    @RequestMapping("login")
    ResponseMsg login(String account, String password){
        System.out.println("account:"+account+"\npassword:"+password);
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        //数据库查询的条件
        wrapper.eq("phone",account).or()
                .eq("nickname",account);
        //数据库根据手机号查询对应的用户
        Users ret = usersService.getOne(wrapper);
        if(null != ret){
            //加密次数赋值
            int count = ret.getRepwdTimes()==null? 1: ret.getRepwdTimes();
            //加密账号输入的密码
            String pwd = DigestUtils.md5DigestAsHex((password+(ret.getSalt()==null?"":ret.getSalt())).getBytes());
            for (int i = 0; i < count-1; i++){
                pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
            }
            //比较加密后的输入密码和数据库加密密码
            System.out.println("输入密码的加密后："+pwd+"\n数据库加密后的密码；"+ret.getPassword());
            if(!pwd.equals(ret.getPassword())){
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"账号或密码输入错误");
            }
            //token的保存时间
            long time = 3600L *  100000;
            String token = JwtUtils.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(ret),time);
            //将登录的用户数据保存redis中
            redisUtils.set(ret.getUserId().toString(),token,time);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"登录成功",token);
        }
        return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"账号不存在");
    }

    /**
     *      在数据库中添加新的用户对象
     * @param users 需添加的用户对象
     * @return  添加是否成功
     */
    @RequestMapping("add")
    ResponseMsg add(@RequestBody Users users){
        Random random = new Random();
        //随机盐
        users.setSalt(generateRandomString(random.nextInt(5)+5));
        //随机加密次数
        users.setRepwdTimes(random.nextInt(8)+14);
        //第一次加密
        String pwd = DigestUtils.md5DigestAsHex((users.getOriginalpwd() + users.getSalt()).getBytes());
        //多次加密
        for (int i = 0; i< users.getRepwdTimes()-1; i++){
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        }
        users.setPassword(pwd);
        return usersService.save(users)?ResponseMsg.getInstance(ResponseMsg.SUCCESS,"添加账号成功",users.getUserId()):
                ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"添加失败");
    }

    /**
     *      数据库查询该手机号是否存在
     * @param phone 手机号
     * @return  返回存在与否
     */
    @RequestMapping("selByPhone")
    ResponseMsg selByPhone(String phone){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        Users users = usersService.getOne(wrapper);
        System.out.println(users);
        return null == users?ResponseMsg.success("未有重复的手机号"):
                ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"手机号已存在");
    }

    /**
     *      数据库中查询该用户名昵称是否存在
     * @param nickname  用户名昵称
     * @return  返回存在与否
     */
    @RequestMapping("selByNickname")
    ResponseMsg selByNickname(String nickname){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("nickname",nickname);
        Users users = usersService.getOne(wrapper);
        System.out.println(users);
        return null == users?ResponseMsg.success("未有重复的昵称"):
                ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"昵称已存在");
    }

    /**
     *      根据用户名或手机号在数据库中查询用户id
     * @param account   用户名或手机号
     * @return  用户id
     */
    @RequestMapping("selIdByPhoneOrNickname")
    ResponseMsg selIdByPhoneOrNickname(String account){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",account).or()
                .eq("nickname",account);
        Users users = usersService.getOne(wrapper);
        if(null != users){
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"存在该用户",users.getUserId());
        }
        return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"手机号或用户名输入错误");
    }

    /**
     *      根据id查询用户信息
     * @param userId    用户id
     * @return  用户信息
     */
    @RequestMapping("selById")
    ResponseMsg selById(String userId){
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"获取用户信息",usersService.getById(userId));
    }

    /**
     *      在数据库中修改用户信息
     * @param users 修改后的用户 或者需要修改的用户属性内的信息
     * @return  修改成功与否
     */
    @RequestMapping("revise")
    ResponseMsg revise(@RequestBody Users users){
        return usersService.updateById(users)?ResponseMsg.success("修改成功"):
                ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"修改失败数据异常");
    }

    /**
     * 生成指定长度的随机字符串（a-z）
     * @param length 所需字符串的长度
     * @return 随机生成的字符串
     */
    private  String generateRandomString(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0");
        }

        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            // 生成 0-25 的随机数，加上 'a' 的 ASCII 值，得到 a-z 之间的字符
            char randomChar = (char) ('a' + random.nextInt(26));
            sb.append(randomChar);
        }

        return sb.toString();
    }

    @GetMapping("/getOneUsers/{userId}")
    ResponseMsg getOneUsers(@PathVariable Integer userId){
        System.out.println("用户Id: " + userId);
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Users users = usersService.getOne(wrapper);
        if (null == users){
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "该用户不存在");
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查找成功", users);
    }

    @RequestMapping("updateUser")
    ResponseMsg updateUser(@RequestBody Users users){
        UpdateWrapper<Users> wrapper = new UpdateWrapper<>();
        wrapper.set(users.getPhone() != null, "phone", users.getPhone())
                .set(users.getOriginalpwd() != null, "originalpwd", users.getOriginalpwd())
                .set(users.getPassword() != null, "password", users.getPassword())
                .set(users.getRepwdTimes() != null, "repwd_times", users.getRepwdTimes())
                .set(users.getNickname() != null, "nickname", users.getNickname())
                .set(users.getAvatar() != null, "avatar", users.getAvatar())
                .set(users.getGender() != null, "gender", users.getGender())
                .set(users.getBirthday() != null, "birthday", users.getBirthday())
                .set(users.getBuilding() != null, "building", users.getBuilding())
                .set(users.getUnit() != null, "unit", users.getUnit())
                .set(users.getRoom() != null, "room", users.getRoom())
                .set((users.getPoints() != null && users.getPoints() >= 0) , "points", users.getPoints())
                .set(users.getCreatedAt() != null, "created_at", users.getCreatedAt())
                .set(users.getUpdatedAt() != null, "updated_at", users.getUpdatedAt())
                .set(users.getStatus() != null, "status", users.getStatus())
                .eq("user_id", users.getUserId());
        if (usersService.update(wrapper)) {
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改成功", users);
        }
        return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "修改失败");
    }

    /**
     * 从Redis中获取用户ID（通过JWT token）
     */
    private Integer getUserIdFromToken(String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            Claims claims = JwtUtils.parseJWT(token);
            String userJson = claims.getSubject();
            Users user = JSON.parseObject(userJson, Users.class);
            return user.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从Redis中获取用户ID（通过token key）
     */
    private Integer getUserIdFromRedis(String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            // 解析token获取用户信息
            Claims claims = JwtUtils.parseJWT(token);
            String userJson = claims.getSubject();
            Users user = JSON.parseObject(userJson, Users.class);

            // 验证token是否在Redis中存在且有效
            String redisToken = (String) redisUtils.get(user.getUserId().toString());
            if (redisToken != null && redisToken.equals(token)) {
                return user.getUserId();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取我的帖子列表（分页）- 从Redis获取用户ID
     */
    @RequestMapping("showMyPosts")
    public ResponseMsg myPosts(HttpServletRequest request,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {

        System.out.println("=== 开始处理showMyPosts请求 ===");

        // 1. 从请求头获取token
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getHeader("Token");
        }
        if (token == null) {
            token = request.getHeader("Authorization");
        }

        System.out.println("获取到的token: " + token);

        // 2. 验证token是否存在
        if (token == null || token.trim().isEmpty()) {
            System.out.println("token为空，返回错误");
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "未提供身份凭证");
        }

        try {
            // 3. 解析JWT获取用户ID
            Claims claims = JwtUtils.parseJWT(token);
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);
            Integer userId = tokenUser.getUserId();

            System.out.println("解析出的用户ID: " + userId);

            // 4. 验证Redis中的token有效性 - 修复类型转换
            Object redisTokenObj = redisUtils.get(userId.toString());
            String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;

            System.out.println("Redis中的token: " + redisToken);

            if (redisToken == null || !redisToken.equals(token)) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
            }

            // 5. 查询用户帖子
            Page<Posts> pageParam = new Page<>(page, size);
            QueryWrapper<Posts> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId)
                    .ne("status", 3) // 排除已删除的帖子
                    .orderByDesc("created_at");

            IPage<Posts> postsPage = postsService.page(pageParam, wrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", postsPage.getRecords());
            result.put("total", postsPage.getTotal());
            result.put("size", postsPage.getSize());
            result.put("current", postsPage.getCurrent());
            result.put("pages", postsPage.getPages());

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, result);

        } catch (Exception e) {
            System.out.println("处理帖子请求异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
        }
    }

    /**
     * 获取兑换记录（分页）
     */
    @RequestMapping("showRedemptionRecords")
    public ResponseMsg showRedemptionRecords(HttpServletRequest request,
                                             @RequestParam(defaultValue = "1") Integer page,
                                             @RequestParam(defaultValue = "10") Integer size,
                                             @RequestParam(required = false) Integer status) {

        System.out.println("=== 开始处理showRedemptionRecords请求 ===");

        // 1. 从请求头获取token
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getHeader("Token");
        }
        if (token == null) {
            token = request.getHeader("Authorization");
        }

        System.out.println("获取到的token: " + token);

        if (token == null || token.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "未提供身份凭证");
        }

        try {
            // 2. 解析JWT获取用户ID
            Claims claims = JwtUtils.parseJWT(token);
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);
            Integer userId = tokenUser.getUserId();

            // 3. 验证Redis中的token
            Object redisToken = redisUtils.get(userId.toString());
            if (redisToken == null || !redisToken.equals(token)) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
            }

            // 4. 查询兑换记录
            Page<MallOrders> pageParam = new Page<>(page, size);
            QueryWrapper<MallOrders> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);

            if (status != null) {
                wrapper.eq("status", status);
            }

            wrapper.orderByDesc("created_at");

            IPage<MallOrders> ordersPage = mallOrdersService.page(pageParam, wrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", ordersPage.getRecords());
            result.put("total", ordersPage.getTotal());
            result.put("size", ordersPage.getSize());
            result.put("current", ordersPage.getCurrent());
            result.put("pages", ordersPage.getPages());

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, result);

        } catch (Exception e) {
            System.out.println("处理兑换记录请求异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
        }
    }

    /**
     * 获取兑换统计信息
     */
    @RequestMapping("getExchangeStats")
    public ResponseMsg getExchangeStats(HttpServletRequest request) {

        System.out.println("=== 开始处理getExchangeStats请求 ===");

        // 1. 从请求头获取token
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getHeader("Token");
        }
        if (token == null) {
            token = request.getHeader("Authorization");
        }

        System.out.println("获取到的token: " + token);

        if (token == null || token.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "未提供身份凭证");
        }

        try {
            // 2. 解析JWT获取用户ID
            Claims claims = JwtUtils.parseJWT(token);
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);
            Integer userId = tokenUser.getUserId();

            // 3. 验证Redis中的token - 修复类型转换
            Object redisTokenObj = redisUtils.get(userId.toString());
            String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;

            System.out.println("Redis中的token: " + redisToken);

            if (redisToken == null || !redisToken.equals(token)) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
            }

            // 4. 统计各种状态的订单数量
            Map<String, Object> stats = new HashMap<>();

            QueryWrapper<MallOrders> totalWrapper = new QueryWrapper<>();
            totalWrapper.eq("user_id", userId);
            stats.put("total", mallOrdersService.count(totalWrapper));

            QueryWrapper<MallOrders> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("user_id", userId).eq("status", 1);
            stats.put("pending", mallOrdersService.count(pendingWrapper));

            QueryWrapper<MallOrders> deliveringWrapper = new QueryWrapper<>();
            deliveringWrapper.eq("user_id", userId).eq("status", 2);
            stats.put("delivering", mallOrdersService.count(deliveringWrapper));

            QueryWrapper<MallOrders> completedWrapper = new QueryWrapper<>();
            completedWrapper.eq("user_id", userId).eq("status", 3);
            stats.put("completed", mallOrdersService.count(completedWrapper));

            QueryWrapper<MallOrders> favoritedWrapper = new QueryWrapper<>();
            favoritedWrapper.eq("user_id", userId).eq("status", 4);
            stats.put("favorited", mallOrdersService.count(favoritedWrapper));

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, stats);

        } catch (Exception e) {
            System.out.println("处理统计请求异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
        }
    }
    // 修改密码接口
    @RequestMapping("changePassword")
    public ResponseMsg changePassword(HttpServletRequest request, @RequestBody Map<String, String> params) {
        try {
            // 1. 获取token和验证
            String token = request.getHeader("token");
            if (token == null || token.trim().isEmpty()) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "未提供身份凭证");
            }

            // 2. 解析token获取用户信息
            Claims claims = JwtUtils.parseJWT(token);
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);

            // 3. 验证Redis中的token
            Object redisToken = redisUtils.get(tokenUser.getUserId().toString());
            if (redisToken == null || !redisToken.equals(token)) {
                return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "无效的凭证");
            }

            // 4. 获取请求参数
            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "参数不能为空");
            }

            if (newPassword.length() < 6) {
                return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "新密码长度不能少于6位");
            }

            // 5. 查询数据库中的用户信息
            Users dbUser = usersService.getById(tokenUser.getUserId());
            if (dbUser == null) {
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "用户不存在");
            }

            // 6. 验证原密码
            String encryptedOldPassword = DigestUtils.md5DigestAsHex(
                    (oldPassword + (dbUser.getSalt() == null ? "" : dbUser.getSalt())).getBytes()
            );

            for (int i = 0; i < (dbUser.getRepwdTimes() == null ? 1 : dbUser.getRepwdTimes()) - 1; i++) {
                encryptedOldPassword = DigestUtils.md5DigestAsHex(encryptedOldPassword.getBytes());
            }

            if (!encryptedOldPassword.equals(dbUser.getPassword())) {
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "原密码错误");
            }

            // 7. 加密新密码
            String salt = UUID.randomUUID().toString().substring(0, 8);
            String encryptedNewPassword = DigestUtils.md5DigestAsHex((newPassword + salt).getBytes());

            // 8. 更新用户信息
            Users updateUser = new Users();
            updateUser.setUserId(dbUser.getUserId());
            updateUser.setPassword(encryptedNewPassword);
            updateUser.setSalt(salt);
            updateUser.setRepwdTimes(1);
            updateUser.setOriginalpwd(newPassword);

            boolean updateResult = usersService.updateById(updateUser);
            if (updateResult) {
                // 9. 清除Redis中的token，强制重新登录
                redisUtils.del(dbUser.getUserId().toString());

                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "密码修改成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, "密码修改失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, "密码修改失败");
        }
    }

    // 退出登录接口
    @RequestMapping("logout")
    public ResponseMsg logout(HttpServletRequest request) {
        try {
            // 1. 获取token
            String token = request.getHeader("token");
            if (token == null || token.trim().isEmpty()) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "退出成功");
            }

            // 2. 解析token获取用户ID
            Claims claims = JwtUtils.parseJWT(token);
            Users tokenUser = JSON.parseObject(claims.getSubject(), Users.class);

            // 3. 清除Redis中的token
            redisUtils.del(tokenUser.getUserId().toString());

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "退出登录成功");

        } catch (Exception e) {
            // 即使解析失败也返回成功，因为目的是退出
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "退出成功");
        }
    }


    //更新用户信息
    @RequestMapping("updateUserInfo")
    ResponseMsg updateUserInfo(@RequestBody Users user, HttpServletRequest request){

        long time = 3600L *  100000;
        String token = JwtUtils.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(user),time);
        //将登录的用户数据保存redis中
        redisUtils.set(user.getUserId().toString(),token,time);
        usersService.updateById(user);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "更新成功", token);
    }
}
